package cn.oms.auth.provider.service.impl;

import cn.oms.auth.api.dto.req.CheckEmailReq;
import cn.oms.auth.api.dto.req.RegisterReq;
import cn.oms.auth.api.dto.res.PermissionRes;
import cn.oms.auth.api.dto.res.RoleRes;
import cn.oms.auth.api.dto.res.UserRes;
import cn.oms.auth.api.service.IUserService;
import cn.oms.auth.provider.dao.entity.Permission;
import cn.oms.auth.provider.dao.entity.Role;
import cn.oms.auth.provider.dao.entity.User;
import cn.oms.auth.provider.dao.entity.UserRole;
import cn.oms.auth.provider.dao.mapper.UserMapper;
import cn.oms.auth.provider.dao.mapper.UserRoleMapper;
import cn.oms.esb.api.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AllenChen曾晨
 * @since 2022-04-12
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 用户注册接口
     * @param registerReq
     */
    @Override
    public String registerUser(RegisterReq registerReq) {
        Map<String, String> params = new HashMap<>();

        // 检查用户是否存在
        if (registerReq.getUsername()==null){
            //抛出异常
            throw new ServiceException("用户名不能为空!");
        }
        User user=userMapper.findUserByUsername(registerReq.getUsername());
        if (user!=null){
            throw new ServiceException("用户名已被注册！！");
        }

        // 检查邮箱是否被注册
        if (registerReq.getEmail()==null){
            //抛出异常
            throw new ServiceException("邮箱不能为空!");
        }
        User user1=userMapper.findUserByUserEmail(registerReq.getEmail());
        if (user1!=null){
            throw new ServiceException("邮箱已被注册！！");
        }

        // 检查邮箱验证码是否正确
        if (registerReq.getVerification()==null){
            //抛出异常
            throw new ServiceException("验证码不能为空!");
        }
        String url="http://esb-service/esb/email/api/checkEmailVerification/{1}";
        String res=restTemplate.getForObject(url,String.class,registerReq.getVerification());
        if (!"true".equals(res)){
            //抛出异常
            throw new ServiceException("验证码不正确!");
        }

        if (!registerReq.getPassword().equals(registerReq.getConfirm())){
            //抛出异常
            throw new ServiceException("两次密码不匹配!");
        }
        // 密码加密
        PasswordEncoder encoder=new BCryptPasswordEncoder();
        String pwd="{bcrypt}"+encoder.encode(registerReq.getPassword());

        //实例化User对象进行相关属性的赋值
        User user3=new User();
        user.setUserId(UUID.randomUUID().toString());
        user.setUserName(registerReq.getUsername());
        user.setUserEmail(registerReq.getEmail());
        user.setUserName(pwd);
        user.setEnabled(1);//可用
        user.setLocked(0);//不锁定
        user.setCreateTime(new Date()); //当前时间
        user.setUserType(0); //普通用户
        user.setDelFlag(0); //删除标记
        //将用户新增到数据库
        int num = userMapper.insert(user);
        // num是增删改操作对数据库产生影响的行数,新增一般就是1,如果返回0表示新增失败
        if(num==0){
            log.info("数据库新增用户失败！！！");
            throw new ServiceException("数据库异常");
        }
        //8.新增用户和角色的关系
        UserRole authUserRole=new UserRole();
        authUserRole.setUserId(user.getUserId());
        authUserRole.setRoleId(1);
        num=userRoleMapper.insert(authUserRole);
        if(num==0){
            log.info("数据库新增用户权限失败！！！");
            throw new ServiceException("数据库异常");
        }

        return "111";
    }


    /**
     * 根据用户名获取用户
     * @param username
     * @return
     */
    @Override
    public UserRes getUserByUsername(String username) {
        UserRes userRes = new UserRes();
        User user = userMapper.findUserByUsername(username);
        BeanUtils.copyProperties(user,userRes);
        return userRes;
    }

    /**
     * 根据用户ID获取权限
     * @param id
     * @return
     */
    @Override
    public List<PermissionRes> getPermissionsById(Integer id) {
        List<PermissionRes> permissionResList = new ArrayList<>();
        List<Permission> permissionList = userMapper.findUserPermissionsById(id);
        for (Permission p: permissionList) {
            PermissionRes permissionRes = new PermissionRes();
            BeanUtils.copyProperties(p,permissionRes);
            permissionResList.add(permissionRes);
        }
        return permissionResList;
    }

    /**
     * 根据用户ID获取角色
     * @param id
     * @return
     */
    @Override
    public List<RoleRes> getRolesById(Integer id) {
        List<RoleRes> roleResList = new ArrayList<>();
        List<Role> roleList = userMapper.findUserRolesById(id);
        for (Role r: roleList) {
            RoleRes roleRes = new RoleRes();
            BeanUtils.copyProperties(r,roleRes);
            roleResList.add(roleRes);
        }
        return roleResList;
    }

    /**
     * 用户注册验证邮箱
     * @param checkEmailReq
     * @return
     */
    @Override
    public String registerCheckEmail(CheckEmailReq checkEmailReq) {
        return null;
    }

}
